/**
 * Created by De Niro on 2015/10/15.
 */
app.config(['$httpProvider',function($httpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

        for(name in obj) {
            value = obj[name];

            if(value instanceof Array) {
                for(i=0; i<value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if(value instanceof Object) {
                for(subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if(value !== undefined && value !== null)
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }

        return query.length ? query.substr(0, query.length - 1) : query;
    };

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
}]);
app.controller('doctorLoginController',function($scope,$http){
    $scope.username = "";
    $scope.password = "";
    $scope.error = "";
    $scope.submit = function() {
        $http.post('php/doctor.php?action=doctorLogin',
            {
                username:$scope.username,
                password:$scope.password
            }).success(function(data) {
                if(data.status=='failed'){
                    $scope.error = true;
                }else{
                    $scope.error = false;
                    window.location.href = "patientInformation.html";
                }
            });
    }
    $scope.backward = function(){
        window.location.href = 'index.php';
    }
}).controller('patientInfoFillController',function($scope,$http){
    $scope.name = "";
    $scope.sex = 'none';
    $scope.birthday = "";
    $scope.telephone = "";
    $scope.medicareCard = "";
    $scope.registrationNumber = "";
    $scope.conditionDescription = "";
    $scope.inputInfo = function(target){
        $(target).closest('div').addClass('active');
        $(target).closest('div').find('.in').focus();
    };
    $scope.stopInput = function(target){
        $(target).closest('div').removeClass('active');
    }
    $scope.submit = function() {
        $http.post('php/patient.php?action=newResume',
            {
                name:$scope.name,
                sex:$scope.sex,
                birthday:$scope.birthday,
                telephone:$scope.telephone,
                medicareCard:$scope.medicareCard,
                registrationNumber:$scope.registrationNumber,
                conditionDescription:$scope.conditionDescription
            }).success(function(data) {
                if(data.status=='failed'){
                    alert("信息上传失败");
                }else{
                    window.location.href = "submitSuccess.html";
                }
            });
    }
    $scope.backward = function(){
        window.history.go(-1);
    }
}).controller('submitSuccessController',function($scope){
    //有bug要改
    $scope.backward = function(){
        window.history.go(-1);
    }
    $scope.ok = function(){
        window.location.href = "station.html";//此处要改
    }
}).controller('patientInformationController',function($scope,$http){
    $scope.patientList = "";
    $scope.patientListRaw = "";
    $scope.keyword = "";
    $scope.sexCode2Str =  sexCode2Str;
    $scope.ageCode2Str = ageCode2Str;
    $scope.search = function(){
        var length = $scope.patientListRaw.length;
            if($scope.keyword == ""){
                $scope.patientList = $scope.patientListRaw;
            }else{
                $scope.patientList = [];
                var i = 0;
                for(;i<length;i++){
                    if(($scope.patientListRaw[i]['patientName'].indexOf($scope.keyword)>-1)||($scope.patientListRaw[i]['transferID']&&$scope.patientListRaw[i]['transferID'].indexOf($scope.keyword)>-1)||($scope.patientListRaw[i]['hospital']&&$scope.patientListRaw[i]['hospital'].indexOf($scope.keyword)>-1)){
                        $scope.patientList.push($scope.patientListRaw[i]);
                    }
                }
            }
    }

    $http.get('php/doctor.php?action=patientSearch').success(function(data){
        $scope.patientListRaw = $scope.patientList = data.data;
    });
    $scope.cutTime = function(timeString){
        return timeString.substring(0,timeString.indexOf(' '));
    }
    $scope.backward = function(){
        window.location.href = "doctorLogin.html";
    }
}).controller('patientResumeController',function($scope,$http,$location){
    $scope.backward = function(){
        window.history.go(-1);
    }
    $scope.details = "";
    $scope.sexCode2Str =  sexCode2Str;
    $scope.ageCode2Str = ageCode2Str;
    var hrefSearch = window.location.href,
        patientId = hrefSearch.substr(hrefSearch.indexOf('=')+1);
    $http.get('php/patient.php?action=detail&id='+patientId).success(function(data){
        if(data.status=='failed'){
            alert("信息上传失败");
        }else{
            $scope.details = data.data;
        }
    });
    $scope.cutTime = function(timeString){
        return timeString&&timeString.substring(0,timeString.indexOf(' '));
    }
}).controller('patientTransferController',function($scope,$http,$location,$rootScope){
    var hrefSearch = window.location.href,
        patientId /*= hrefSearch.substr(hrefSearch.indexOf('=')+1)*/,
        reTransfer = (hrefSearch.indexOf('reTransfer') > -1);
    if(reTransfer){
        patientId = hrefSearch.substring(hrefSearch.indexOf('=')+1,hrefSearch.indexOf('&'));
    }else{
        patientId = hrefSearch.substr(hrefSearch.indexOf('=')+1);
    }
    $rootScope.reTransfer = reTransfer;
    $rootScope.patientId = patientId;
    $rootScope.diagnose = "";
    $rootScope.transferToDoctor = "";
    $rootScope.cutTime = function(timeString){
        return timeString&&timeString.substring(0,timeString.indexOf(' '));
    }
    $scope.backward = function(){
        window.history.go(-1);
    }
    $rootScope.sexCode2Str =  sexCode2Str;
    $rootScope.ageCode2Str = ageCode2Str;
    $http.get('php/patient.php?action=detail&id='+$rootScope.patientId).success(function(data){
        if(data.status=='failed'){
            alert("信息上传失败");
        }else{
            $rootScope.details = data.data;
        }
    });
}).controller('patientDiagnoseController',function($scope,$http,$rootScope){
    $scope.diagnose = "";
    $scope.submit = function(){
        if(!$scope.diagnose){
            alert("请填写诊断");
            return;
        }
        $rootScope.diagnose = $scope.diagnose ;
        window.location.href = '#/patientData';
    }
}).controller('patientDataController',function($scope){
    $scope.nextStep = function(){
        window.location.href = '#/chooseDoctor';
    }
}).controller('chooseDoctorController',function($scope,$http,$rootScope){
    $scope.city = '北京';
    $scope.doctorList = '';
    $scope.transferCity = function(){
        $http.get('php/doctor.php?action=availableDoctor&location='+$scope.city).success(function(data){
            $scope.doctorList = data.data;
        });
    }
    $http.get('php/doctor.php?action=availableDoctor&location='+$scope.city).success(function(data){
        $scope.doctorList = data.data;
    });
    $scope.chosenDoctor = "";
    $scope.switchChoose = function(doctor){
        var temp;
        switch(doctor.chosen){
            case undefined:
                //选择的是一个可选的,则把其他的都置为不可选择的然后将这个选中的置为'chosen'
                for(temp in $scope.doctorList){
                    if($scope.doctorList.hasOwnProperty(temp)){
                        $scope.doctorList[temp].chosen = 'unChosenable';
                    }
                }
                doctor.chosen = 'chosen';
                $scope.chosenDoctor = doctor.id;
                //console.log($scope.doctorList);
                return;
            case 'chosen':
                //选择的是一个已选中的,则将所有都置为可选的
                for(temp in $scope.doctorList){
                    if($scope.doctorList.hasOwnProperty(temp)){
                        $scope.doctorList[temp].chosen = undefined;
                    }
                }
                $scope.chosenDoctor = "";
                return;
            case 'unChosenable':
                for(temp in $scope.doctorList){
                    if($scope.doctorList.hasOwnProperty(temp)){
                        $scope.doctorList[temp].chosen = 'unChosenable';
                    }
                }
                doctor.chosen = 'chosen';
                return;
        }
    }
    $scope.nextStep = function(){
        if(!$scope.chosenDoctor){
            alert('请选择一位转诊医生');
        }else{
            if(!$rootScope.reTransfer){
                $http.post('php/doctor.php?action=transfer',
                    {
                        resumeID:$rootScope.patientId,
                        transferDoctorID:$scope.chosenDoctor,
                        transferDiagnosis:$rootScope.diagnose,
                    }).success(function(data) {
                        if(data.status=='success'){
                            alert('成功发起');
                            window.location.href = "patientInformation.html";
                        }else{
                            alert('转诊失败');
                        }
                    });
            }else{
                $http.post('php/doctor.php?action=reTransfer',
                    {
                        resumeID:$rootScope.patientId,
                        transferDoctorID:$scope.chosenDoctor,
                        transferDiagnosis:$rootScope.diagnose,
                    }).success(function(data) {
                        if(data.status=='success'){
                            alert('重新发起成功');
                            window.location.href = "patientInformation.html";
                        }else{
                            alert('转诊失败');
                        }
                    });
            }
        }
    }
}).controller('transferQueryController',function($scope){
    $scope.backward = function(){
        window.location.href = 'patientInformation.html';
    }
    $scope.sexCode2Str =  sexCode2Str;
    $scope.ageCode2Str = ageCode2Str;
    $scope.cutTime = function(timeString){
        return timeString&&timeString.substring(0,timeString.indexOf(' '));
    }
}).controller('ensureController',function($scope,$http){
    $scope.patientList = "";
    $http.get('php/doctor.php?action=waitingSure').success(function(data){
        $scope.patientList = data.data;
    });
    $scope.cancel = function(patient){
        $http.get("php/doctor.php?action=transferCancel&resumeID="+patient['resumeID']).success(function(data){
                if(data.status=='success'){
                    $http.get('php/doctor.php?action=waitingSure').success(function(data){
                        $scope.patientList = data.data;
                    });
                }else{
                    alert('取消失败');
                }
            }
        );
    };
    $scope.ensureOrAgain = function(patient){
        if(patient['transferMark']=='1'){
            //出
            window.location.href = "patientTransfer.html?patientId="+patient['resumeID']+'&reTransfer';
        }else{
            $http.get("php/doctor.php?action=true&resumeID="+patient['resumeID']).success(function(data){
                if(data.status=='success'){
                    $http.get('php/doctor.php?action=waitingSure').success(function(data){
                        $scope.patientList = data.data;
                    });
                }else{
                    alert('操作失败');
                }
            });
        }
    }
}).controller('cureController',function($scope,$http){
    $scope.patientList = "";
    $http.get('php/doctor.php?action=waitingResume').success(function(data){
        $scope.patientList = data.data;
    });
    $scope.finish = function(patient){
        $http.get('php/doctor.php?action=finish&resumeID='+patient['resumeID']+'&kind='+patient['transferMark']).success(function(data){
            if(data.status=='success'){
                $http.get('php/doctor.php?action=waitingResume').success(function(data){
                    $scope.patientList = data.data;
                });
            }else{
                alert('操作失败');
            }
        });
    }
}).controller('detailsController',function($scope,$http){
    $scope.backward = function(){
        window.history.go(-1);
    }
    $scope.sexCode2Str =  sexCode2Str;
    $scope.ageCode2Str = ageCode2Str;
    $scope.cutTime = function(timeString){
        return timeString&&timeString.substring(0,timeString.indexOf(' '));
    }
    var hrefSearch = window.location.href,
        resumeId = hrefSearch.substring(hrefSearch.indexOf('=')+1,hrefSearch.indexOf('&'));
    $scope.details = "";
    $scope.transferFromMe = (window.location.href[window.location.href.length-1]=='1');
    $http.get('php/patient.php?action=transferDetail&id='+resumeId).success(function(data){
        if(data.status=='success'){
            $scope.details = data.data;
        }else{
            alert('操作失败');
        }
    });
});

function sexCode2Str(sexCode){
    if(sexCode == 0){
        return '男';
    }else{
        return '女';
    }
}
function ageCode2Str(ageCode){
    if(ageCode){
        return (2015-ageCode);
    }
}